package Exam;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

class Car extends Thread {
    private String name = null;
    private Semaphore sp = null;


    public Car(Semaphore sp, String name) {
        this.name = name;
        this.sp = sp;
    }

    Queue<Car> queue = new LinkedList<Car>();

    @Override
    public void run() {
        try {
            sp.acquire();

            System.out.println(Thread.currentThread().getName() + "正在停车");
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "出车位了");
            sp.release();
        }
    }
}

public class SemaphoreTest {
    //第一步:定义一个信号量Semaphore
    static Semaphore sp = new Semaphore(3);

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(Integer.MAX_VALUE / 100);

        for(int i = 0; i < 20; i++){
            service.submit(new Car(sp, "第" + i + "号车"));
        }

        service.shutdown();
    }
}
